import * as type from "@/store/mutations";

export const Common = (http, URI) => {
  const state = {
    isLoading: false,
    errorInfo: {
      error: false,
      tips: ''
    },
    requesting: false,
    // 是否登录
    isLogin: false,
    customer: {},
    investDetail: {}
  };
  const getters = {
    investDetail: state => state.investDetail
  }

  const mutations = {
    [type.UPDATELOADINGSTATE](state, flag) {
      state.isLoading = flag
    },
    [type.REQUEST_START](state) {
      state.requesting = true
      state.errorInfo = {
        error: false,
        tips: ''
      }
    },
    [type.REQUEST_END](state) {
      state.requesting = false
    },
    [type.REQUEST_FAIL](state, tip = "网络异常") {
      state.requesting = false

    },
    updateUserInfo(state, customer) {
      state.customer = customer
    },
    [type.UPDATEINVESTDETAIL](state, invest) {
      state.investDetail = invest;
    }
  };

  const actions = {
    /**
     * post 请求
     * @param commit
     * @param url
     * @param params
     * @param showstatus 控制用什么方式展示
     * @returns {Promise.<*>}
     * @constructor
     */
    async Post({commit}, {url, data, showstatus = false}) {
      commit(type.REQUEST_START);
      const res = await http.post(url, data, showstatus)
      if (res.status === 200) {
        commit(type.REQUEST_END)
      } else {
        commit(type.REQUEST_FAIL, res.statusText)
      }
      return res
    },
    /**
     * get 请求
     * @param commit
     * @param url
     * @param params
     * @param config
     * @returns {Promise.<void>}
     * @constructor
     */
    async Get({commit}, {url, data, showstatus = false}) {
      commit(type.REQUEST_START);
      var res = await http.get(url, data, showstatus);
      if (res.status === 200) {
        commit(type.REQUEST_END)
      } else {
        commit(type.REQUEST_FAIL, res.statusText)
      }
      return res
    },
    GetInvest({commit}, invest) {
      commit(type.UPDATEINVESTDETAIL, invest)

    },
    onLoading({commit}, flag) {
      commit(type.UPDATELOADINGSTATE, flag)
    },
    userInfo({commit}, customer) {
      commit("updateUserInfo", customer);
    }

  };

  return {
    state,
    getters,
    mutations,
    actions
  }
};
